import { http } from '../request'
import type { ApiResponse } from '../request'

// 用户信息接口
export interface UserInfo {
  id: number
  username: string
  nickname: string
  avatar: string
  email: string
  phone: string
  role: string
  status: number
  created_at: string
  updated_at: string
}

// 登录请求参数
export interface LoginParams {
  username: string
  password: string
  remember?: boolean
}

// 登录响应数据
export interface LoginData {
  token: string
  userInfo: UserInfo
  expires: number
}

// 分页查询参数
export interface PaginationParams {
  page: number
  pageSize: number
  keyword?: string
  status?: number
  role?: string
}

// 分页响应数据
export interface PaginationData<T = any> {
  list: T[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

// 用户API模块
export const userAPI = {
  // 用户登录
  login: (params: LoginParams): Promise<ApiResponse<LoginData>> => {
    return http.post('/auth/login', params)
  },
  
  // 用户登出
  logout: (): Promise<ApiResponse<null>> => {
    return http.post('/auth/logout')
  },
  
  // 获取用户信息
  getUserInfo: (): Promise<ApiResponse<UserInfo>> => {
    return http.get('/user/info')
  },
  
  // 更新用户信息
  updateUserInfo: (data: Partial<UserInfo>): Promise<ApiResponse<null>> => {
    return http.put('/user/info', data)
  },
  
  // 修改密码
  changePassword: (data: {
    oldPassword: string
    newPassword: string
    confirmPassword: string
  }): Promise<ApiResponse<null>> => {
    return http.put('/user/password', data)
  },
  
  // 获取用户列表（分页）
  getUserList: (params: PaginationParams): Promise<ApiResponse<PaginationData<UserInfo>>> => {
    return http.get('/users', params)
  },
  
  // 创建用户
  createUser: (data: Omit<UserInfo, 'id' | 'created_at' | 'updated_at'>): Promise<ApiResponse<null>> => {
    return http.post('/users', data)
  },
  
  // 更新用户
  updateUser: (id: number, data: Partial<UserInfo>): Promise<ApiResponse<null>> => {
    return http.put(`/users/${id}`, data)
  },
  
  // 删除用户
  deleteUser: (id: number): Promise<ApiResponse<null>> => {
    return http.delete(`/users/${id}`)
  },
  
  // 批量删除用户
  batchDeleteUsers: (ids: number[]): Promise<ApiResponse<null>> => {
    return http.delete('/users/batch', { ids })
  },
  
  // 上传头像
  uploadAvatar: (file: File): Promise<ApiResponse<{ url: string }>> => {
    return http.upload('/user/avatar', file)
  },
  
  // 获取用户操作日志
  getUserLogs: (params: {
    userId: number
    page: number
    pageSize: number
    startTime?: string
    endTime?: string
  }): Promise<ApiResponse<PaginationData<any>>> => {
    return http.get('/user/logs', params)
  }
}